package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.heima.homeservicemanagementsystem.entity.UserAddress;
import com.heima.homeservicemanagementsystem.service.UserAddressService;

import java.util.List;
import java.util.Objects;

import static cn.dev33.satoken.SaManager.log;

/**
 * 地址;(user_address)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2025-4-10
 */
@Slf4j
@Tag(name = "地址对象功能接口")
@RestController
@RequestMapping("/userAddress")
public class UserAddressController {

    @Resource
    private UserAddressService userAddressService;

    @Operation(summary = "分页查询")
    @PostMapping("/page")

    public Result<Page<UserAddress>> paginQuery(@RequestBody PageParams<UserAddress> pageParams) {
        //查询参数
        UserAddress params = pageParams.getParams();
        LambdaQueryWrapper<UserAddress> lqw = new LambdaQueryWrapper<>();


        lqw.eq(params.getName() != null, UserAddress::getName, params.getName());


        lqw.eq(params.getTel() != null, UserAddress::getTel, params.getTel());


        lqw.eq(params.getRegion() != null, UserAddress::getRegion, params.getRegion());


        lqw.eq(params.getDetailed() != null, UserAddress::getDetailed, params.getDetailed());


        lqw.eq(params.getUserId() != null, UserAddress::getUserId, params.getUserId());


        lqw.eq(params.getIsDefault() != null, UserAddress::getIsDefault, params.getIsDefault());

        return Result.success(userAddressService.page(pageParams.getPage(), lqw));
    }


    @Operation(summary = "地址所有搜索")
    @GetMapping("/list")

    public Result searchQuery() {
//        List<UserAddress> list = userAddressService.list();
        return Result.success(userAddressService.list());
    }

    @Operation(summary = "根据id搜索")
    @GetMapping("/listbyid")
    @Cacheable(value = "userAddress", key = "T(cn.dev33.satoken.stp.StpUtil).getLoginIdAsString()")
    public Result searchQueryByid() {
//        List<UserAddress> list = userAddressService.list();
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", StpUtil.getLoginIdAsString());
        return Result.success(userAddressService.list(wrapper));
    }

    @Operation(summary = "有条件的搜索")
    @PostMapping("/tjSearch")
    public Result Query(@RequestBody UserAddress userAddress) {
        log.info("条件搜索信息：{}", userAddress);
        LambdaQueryWrapper<UserAddress> lqw = new LambdaQueryWrapper<>();


        lqw.eq(StringUtils.hasLength(userAddress.getId()), UserAddress::getId, userAddress.getId());


        lqw.like(StringUtils.hasLength(userAddress.getName()), UserAddress::getName, userAddress.getName());


        lqw.eq(StringUtils.hasLength(userAddress.getTel()), UserAddress::getTel, userAddress.getTel());


//        lqw.eq(userAddress.getRegion() != null, UserAddress::getRegion, userAddress.getRegion());


//        lqw.eq(userAddress.getDetailed() != null, UserAddress::getDetailed, userAddress.getDetailed());


        lqw.eq(StringUtils.hasLength(userAddress.getUserId()), UserAddress::getUserId, userAddress.getUserId());


        lqw.eq(StringUtils.hasLength(userAddress.getIsDefault()), UserAddress::getIsDefault, userAddress.getIsDefault());


        return Result.success(userAddressService.list(lqw));
    }

    /**
     * 新增数据
     *
     * @param userAddress 实例对象
     * @return 实例对象
     */
    @Operation(summary = "新增数据")
    @PostMapping("/insert")
    @CacheEvict(value = "userAddress", key = "T(cn.dev33.satoken.stp.StpUtil).getLoginIdAsString()")
    public Result<Boolean> insert(@RequestBody UserAddress userAddress) {
        log.info("前端地址信息：{}", userAddress);
        String loginIdAsString = StpUtil.getLoginIdAsString();
        if (userAddress.getIsDefault().equals("true")) {
            List<UserAddress> userId = userAddressService.getUserId(loginIdAsString);

            if (!userId.isEmpty()) {
                userId.stream().forEach(userAddress1 -> {
                    userAddress1.setIsDefault("false");
                    boolean b = userAddressService.updateById(userAddress1);

                });


            }
        }
        if (StringUtils.hasLength(userAddress.getUserId())) {
            userAddress.setUserId(userAddress.getUserId());
        } else {
            userAddress.setUserId(loginIdAsString);
        }


        if (userAddressService.save(userAddress)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 更新数据
     *
     * @param userAddress 实例对象
     * @return 实例对象
     */
    @Operation(summary = "更新数据")
    @PutMapping("update")
    @CacheEvict(value = "userAddress", key = "T(cn.dev33.satoken.stp.StpUtil).getLoginIdAsString()")
    public Result<Boolean> update(@RequestBody UserAddress userAddress) {
        log.info("前端地址信息：{}", userAddress);
        String loginIdAsString = StpUtil.getLoginIdAsString();
        if (userAddress.getIsDefault().equals("true")) {

            if (StringUtils.hasLength(userAddress.getUserId())) {
                List<UserAddress> userId = userAddressService.getUserId(userAddress.getUserId());

                if (!userId.isEmpty()) {
                    userId.stream().forEach(userAddress1 -> {
                        userAddress1.setIsDefault("false");
                        boolean b = userAddressService.updateById(userAddress1);
                    });
                }
            } else {
                List<UserAddress> userId = userAddressService.getUserId(loginIdAsString);

                if (!userId.isEmpty()) {
                    userId.stream().forEach(userAddress1 -> {
                        userAddress1.setIsDefault("false");
                        boolean b = userAddressService.updateById(userAddress1);
                    });
                }
            }
        }
        log.info("更新数据：{}", userAddress);
        List<UserAddress> userId = userAddressService.getUserIdiSempty(userAddress);
        log.info("z智能机：{}", userId.isEmpty());
        if (userId.isEmpty()) {
            userAddress.setIsDefault("true");
        } else {
            userAddress.setIsDefault("false");
        }


        if (StringUtils.hasLength(userAddress.getUserId())) {
            userAddress.setUserId(userAddress.getUserId());
        } else {
            userAddress.setUserId(loginIdAsString);
        }
        log.info("前端地址信息：{}", userAddress);
        if (userAddressService.updateById(userAddress)) {
            return Result.success();
        }
        return Result.error();
//        if (userAddressService.updateById(userAddress)) {
//            return Result.success();
//        }
//        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据",
            parameters = {
                    @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
            })

    @GetMapping("/delete/{id}")
    @CacheEvict(value = "userAddress", key = "T(cn.dev33.satoken.stp.StpUtil).getLoginIdAsString()")
    public Result<String> deleteById(@PathVariable String id) {
        UserAddress byId = userAddressService.getById(id);
        if (byId.getIsDefault().equals("false")) {
            userAddressService.removeById(id);
            return Result.success();
        }
        userAddressService.removeById(id);
        if (userAddressService.getUserId(StpUtil.getLoginIdAsString()).size() > 0) {
            UserAddress userAddress = userAddressService.getUserId(StpUtil.getLoginIdAsString()).get(0);

            userAddress.setIsDefault("true");

            userAddressService.updateById(userAddress);
            return Result.success("删除成功");
        }


        return Result.error("删除失败");
    }

    @Operation(summary = "多id删除数据")
    @PostMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("前端信息：{}", id);
        if (userAddressService.removeByIds(id)) {
            return Result.success();
        }
        return Result.error();
    }
}